﻿using System;
using Transformable_Engine_v2.Engine.Global;
using Transformable_Engine_v2.Engine.Rendering;
using Transformable_Engine_v2.Engine.Transformable_Math.Geometry;

namespace Transformable_Engine_v2.Engine.GameObjects.Containers.Transformable_controls
{
    public class RepeatingImage : ImageContainer
    {
        /// <summary>
        /// Size of the texture to repeat. 
        /// </summary>
        public TE_Vector2 Size { get; set; }

                /// <summary>
        /// Area of the texture to repeat
        /// </summary>
        public TE_Vector2 Area 
        { 
            set
            {
                Size = new TE_Vector2(value.X * Game.Options.GridSize / (_source.Width * Scale.X), 
                                      value.Y * Game.Options.GridSize / (_source.Height * Scale.Y));
            } 
        }

        /// <summary>
        /// Area of the texture to repeat
        /// </summary>
        public TE_Rectangle AreaRectangle
        { 
            set
            {
                Area = new TE_Vector2(value.Width, value.Height);
            } 
        }

        /// <summary>
        /// Adding children is prohibited for this type of object
        /// </summary>
        /// <param name="children"></param>
        public override void AddChildren(params Container[] children)
        {
            throw new Exception("A repeatingImageContainer cannot have any children");
        }

        /// <summary>
        /// Draw the repeated texture
        /// </summary>
        public override void Draw()
        {
            if(Visible) 
            {
                TE_Vector2 position = AbsolutePosition;

                for (int y = 0; y < Size.Y; y++) {
                    TE_Vector2 currentPosition = position.Offset(0, y * _source.Height * Scale.Y);

                    for (int x = 0; x < Size.X; x++) {
                        _drawableObject.Position = currentPosition.ToVector2f();

                        if (ShaderHandler.HasShader)
                            RenderTargetHandler.GetCurrentRenderTarget().Draw(_drawableObject, ShaderHandler.CurrentShader);
                        else
                            RenderTargetHandler.GetCurrentRenderTarget().Draw(_drawableObject);

                        currentPosition.AddOffset(_source.Width * Scale.X, 0);
                    }
                }

                _drawableObject.Position = position.ToVector2f();
            }
        }
    }
}